package Advance;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.sql.*;
import java.util.Vector;

/**
 * @Description:用JTable展示表结构
 * @Author:AMark
 * @Date: 11/7/2023
 */
public class DisplayTable {
    JFrame frame;
    DefaultTableModel tableModel;
    JTable table;
    Vector vdata = new Vector();
    Vector vcolumn = new Vector();
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String URL = "jdbc:mysql://localhost:3306/hw;?serverTimezone=UTC";
    static final String USER = "root";
    static final String PASSWORD = "zhc20040309";
    public DisplayTable() {
        try {
            //forname用于加载驱动
            Class.forName(JDBC_DRIVER);
            conn = DriverManager.getConnection(URL,USER,PASSWORD);
            //创建语句命令符
            stmt = conn.createStatement();
            rs = stmt.executeQuery("select * from students");
            while(rs.next()) {
                Vector vrow = new Vector();
                vrow.add(rs.getString(1));
                vrow.add(rs.getString(2));
                vdata.add(vrow);
            }
            vcolumn.add("姓名");
            vcolumn.add("年龄");
            tableModel = new DefaultTableModel(vdata, vcolumn);
            table = new JTable(tableModel);
            JScrollPane sp = new JScrollPane(table);
            frame = new JFrame();
            frame.setSize(300, 200);
            frame.add(sp);
            frame.setVisible(true);
        } catch (ClassNotFoundException e) {
            System.out.println("没有找到驱动！");
        } catch (SQLException e) {
            System.out.println("无法找到相应数据表！");
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(null, e.getMessage());
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        new DisplayTable();
    }
}
